package com.ys.chatserver.http.logic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eva.epc.common.util.CommonUtils;
import com.eva.framework.Processor;
import com.eva.framework.dto.SysActionConst;
import com.eva.framework.utils.EndsExceptionFactory;
import com.google.gson.Gson;
import com.ys.chatserver.common.dto.cnst.RetResult;
import com.ys.chatserver.http.logic.dto.JobDispatchConst;
import com.ys.chatserver.http.logic.dto.PageData;
import com.ys.chatserver.http.logic.dto.QueryUserResVO;
import com.ys.chatserver.http.logic.dto.UpdateUserVO;
import com.ys.chatserver.tool.EmptyUtils;
import com.ys.chatserver.tool.IdUtils;
import com.ys.chatserver.tool.MD5Util;

import java.util.*;

public class UserInfoProccessor implements SysActionConst, Processor {

    private Gson gson = new Gson();

    @Override
    public Object process(int job_dispatch_id, int action_id, Object newData, Object oldData, User user) throws Exception {
        Object ret = null;
        String newDataJSON = (String) newData;

        // 处理后台用户管理
        if (job_dispatch_id == JobDispatchConst.LOGIC_GROUP_USER) {
            ret = maintainUserJobDispatcher(action_id, newDataJSON, oldData, user);
        } else {
            throw EndsExceptionFactory.INVALID_JOB_DISPATCHER_ID(job_dispatch_id);
        }
        return ret;
    }

    private Object maintainUserJobDispatcher(int actionId, String newDataJSON, Object oldData, User user) throws Exception {
        int role = getAccountType(user.getUserId());
        switch (actionId) {
            case ACTION_ADD_USER: //添加用户
            {
                if (role != 0 && role != 2) {
                    return gson.toJson(RetResult.failResult("暂无权限！"));
                }
                JSONObject jsonObj = JSONObject.parseObject(newDataJSON);
                String userMail = jsonObj.getString("userMail");
                String nickname = jsonObj.getString("nickname");
                String userPsw = jsonObj.getString("userPsw");
                String userSex = jsonObj.getString("userSex");
                Date registerTime = new Date();
                Integer userStatus = 1;
                String expireTime = jsonObj.getString("expireTime");
                String accountType = jsonObj.getString("accountType");
                if (EmptyUtils.isEmpty(userMail) || EmptyUtils.isEmpty(nickname) || EmptyUtils.isEmpty(userPsw) ||
                        EmptyUtils.isEmpty(accountType) || EmptyUtils.isEmpty(expireTime)) {
                    return gson.toJson(RetResult.failResult("参数错误!"));
                }
                if (exitUser(userMail)) {
                    return gson.toJson(RetResult.failResult("用户名已存在！"));
                }
                if (userPsw.length() < 6 || userPsw.length() > 18) {
                    return gson.toJson(RetResult.failResult("密码长度6~18位！"));
                }
                if (userPsw.matches("[0-9]+")) {
                    return gson.toJson(RetResult.failResult("密码必须包含数字、字母或特殊符号！"));
                }
                userPsw = MD5Util.MD5_32(userPsw);
                List<String> sqls = new ArrayList<>(2);
                List<Object[]> values = new ArrayList<>(2);
                addUserInfo(sqls, values, userMail, nickname, userPsw, userSex, registerTime, userStatus,
                        "0", accountType, expireTime, user.getUserId());
                boolean update = LogicProcessor2.db.update(sqls, values, true);

                return update ? gson.toJson(RetResult.successResult("添加成功!")) : gson.toJson(RetResult.failResult("添加失败!系统异常!"));
            }
            case ACTION_QUERY_USER: { //获取用户列表
                if (role != 0 && role != 2) {
                    return gson.toJson(RetResult.failResult("暂无权限！"));
                }
                JSONObject jsonObj = JSON.parseObject(newDataJSON);
                Integer pageSize = Integer.valueOf(jsonObj.getString("pageSize"));
                Integer pageNumber = Integer.valueOf(jsonObj.getString("pageNumber"));
                String keyword = jsonObj.getString("keyword");
                return queryUserList(user.getUserId(), pageSize, pageNumber, keyword);
            }
            case ACTION_UPDATE_USER: { //修改用户信息
                if (role != 0 && role != 2) {
                    return gson.toJson(RetResult.failResult("暂无权限！"));
                }
                UpdateUserVO vo = JSON.parseObject(newDataJSON, UpdateUserVO.class);
                List<String> sqlList = getSqlList(vo);
                boolean update = LogicProcessor2.db.update(sqlList, true);
                return update ? gson.toJson(RetResult.successResult("修改成功!")) : gson.toJson(RetResult.failResult("修改失败!系统异常!"));
            }
            case ACTION_DELETE_USER: { //删除用户信息
                if (role != 0 && role != 2) {
                    return gson.toJson(RetResult.failResult("暂无权限！"));
                }
                JSONObject jsonObj = JSON.parseObject(newDataJSON);
                final String userUid = jsonObj.getString("userUid");
                return deleteUser(userUid, user.getUserId());
            }
            case ACTION_QUERY_USER_INFO: { //查询用户信息
                JSONObject jsonObj = JSON.parseObject(newDataJSON);
                final String userUid = jsonObj.getString("userUid");
                return queryUserById(userUid);
            }
            case ACTION_UPDATE_USER_PASSWORD: { //修改用户密码
                if (role == 1) {
                    return gson.toJson(RetResult.failResult("暂无权限！"));
                }
                JSONObject jsonObj = JSON.parseObject(newDataJSON);
                final String userUid = jsonObj.getString("userUid");
                String userPsw = jsonObj.getString("userPsw");
                if (userPsw.length() < 6 || userPsw.length() > 18) {
                    return gson.toJson(RetResult.failResult("密码长度6~18位！"));
                }
                if (userPsw.matches("[0-9]+")) {
                    return gson.toJson(RetResult.failResult("密码必须包含数字、字母或特殊符号！"));
                }
                userPsw = MD5Util.MD5_32(userPsw);
                if (role == 0) {
                    String createId = getCreateId(userUid);
                    if (createId == null || !createId.equals(user.getUserId())) {
                        return gson.toJson(RetResult.failResult("暂无权限!"));
                    }
                }
                return updateUserPassword(userUid, userPsw);

            }
            default:
                throw EndsExceptionFactory.INVALID_ACTION_ID(actionId);
        }

    }


    private String updateUserPassword(String userUid, String userPsw) throws Exception {
        String sql = "update g_users set  user_psw = '" + userPsw + "' where user_uid = '" + userUid + "'";
        List<String> strings = new ArrayList<>();
        strings.add(sql);
        boolean update = LogicProcessor2.db.update(strings, true);

        return update ? gson.toJson(RetResult.successResult("修改成功!")) :
                gson.toJson(RetResult.failResult("修改失败!系统异常!"));

    }

    private String queryUserById(String userUid) throws Exception {
        String s = "select u.nickname,u.register_time,u.latest_login_time,u.account_type,u.expire_time," +
                " u.user_uid,u.user_mail,u.user_sex,u.user_status,g.nickname creatorName,u.is_online" +
                "  from g_users u " +
                " left join g_users g on g.user_uid = u.creator_id " +
                " where u.del_flag = 0 and u.user_uid = '" + userUid + "'";
        Vector<Vector<?>> vectors = LogicProcessor2.db.queryData(s);
        QueryUserResVO vo = new QueryUserResVO();
        if (vectors.isEmpty()) {
            vo.setUserUid("-1");
            return new Gson().toJson(RetResult.failResult("账号不存在!"));
        }

        for (Vector<?> v : vectors) {
            int i = 0;
            String nickname = v.get(i).toString();
            String registerTime = v.get(++i).toString();
            String latestLoginTime = v.get(++i).toString();
            String type = v.get(++i).toString();
            String expireTime = v.get(++i).toString();
            String uid = v.get(++i).toString();
            String userMail = v.get(++i).toString();
            String userSex = v.get(++i).toString();
            String userStatus = v.get(++i).toString();
            String creatorName = v.get(++i).toString();
            Integer isOnline = Integer.valueOf(v.get(++i).toString());
            vo.setUserUid(uid);
            vo.setNickname(nickname);
            vo.setRegisterTime(registerTime);
            vo.setAccountType(Integer.valueOf(type));
            vo.setLatestLoginTime(latestLoginTime);
            vo.setExpireTime(expireTime);
            vo.setUserMail(userMail);
            vo.setUserSex(Integer.valueOf(userSex));
            vo.setUserStatus(Integer.valueOf(userStatus));
            vo.setCreatorName(creatorName);
            vo.setIsOnline(isOnline);
        }

        return gson.toJson(RetResult.successResult("查询成功!", vo));
    }

    /**
     * 删除用户/设备
     *
     * @param userUid   被删除人id
     * @param operateId 操作人Id
     */
    private String deleteUser(String userUid, String operateId) throws Exception {
        //查询修改人是否为创建者
        String createId = getCreateId(userUid);
        if (createId == null || !createId.equals(operateId)) {
            return gson.toJson(RetResult.failResult("暂无权限!"));
        }

        //查询用户是否存在
        QueryUserResVO vo = getUserByCreatorId(userUid, operateId);
        if ("-1".equals(vo.getUserUid())) {
            return gson.toJson(RetResult.failResult("删除的账号不存在!"));
        }

        //用户
        if (vo.getUserType() == 0) {
            //是否存在组织中
//            String sql = "select * from structure_user_info where user_id= '" + userUid + "'";
//            Vector<Vector<?>> structureUser = LogicProcessor2.db.queryData(sql);
//
//            //查询是否在群组里面
//            String str = "select * from chat_group_node where node_type = 'USER' and user_uid = '" + userUid + "'";
//            Vector<Vector<?>> groups = LogicProcessor2.db.queryData(str);
//
//            //是否添加用户或者设备
//            String userSql = "select * from g_users where account_type !=1 and creator_id='" + userUid + "'";
//            Vector<Vector<?>> isAddUser = LogicProcessor2.db.queryData(userSql);

            List<String> list = new ArrayList<>();
            //用户不在群组，不在组织，没有添加用户或设备 物理删除
//            if (groups.isEmpty() && structureUser.isEmpty() && isAddUser.isEmpty()) {
            //String s = "delete from g_users where user_uid = '" + userUid + "'";
            String s = "update g_users set del_flag = 1 where user_uid = '" + userUid + "'";
            list.add(s);
            boolean update = LogicProcessor2.db.update(list, true);
            return update ? gson.toJson(RetResult.successResult("删除成功!")) : gson.toJson(RetResult.failResult("删除失败!系统异常!"));
//            }
//            String s = "update g_users set user_status = 0 where user_uid = '" + userUid + "'";
//            list.add(s);
//            boolean update = LogicProcessor2.db.update(list, true);
//            return update ? gson.toJson(RetResult.successResult("账户锁定成功!")) : gson.toJson(RetResult.failResult("账户锁定失败!系统异常!"));

        }

        return gson.toJson(RetResult.failResult("删除失败!"));
    }

    private List<String> getSqlList(UpdateUserVO vo) {
        List<String> sqlList = new ArrayList<>();
        StringBuilder builder = new StringBuilder();
        builder.append("update g_users set");
        if (EmptyUtils.isNotEmpty(vo.getNickname())) {
            builder.append(" nickname = '" + vo.getNickname() + "',");
        }
        if (EmptyUtils.isNotEmpty(vo.getUserSex())) {
            builder.append(" user_sex = '" + vo.getUserSex() + "',");
        }
        if (EmptyUtils.isNotEmpty(vo.getUserStatus())) {
            builder.append(" user_status = '" + vo.getUserStatus() + "',");
        }
//        if (EmptyUtils.isNotEmpty(vo.getUserType())){
//            builder.append(" user_type = '" + vo.getUserType() + "',");
//        }
        if (EmptyUtils.isNotEmpty(vo.getAccountType())) {
            builder.append(" account_type = '" + vo.getAccountType() + "',");
        }
        if (EmptyUtils.isNotEmpty(vo.getDownloadUrl())) {
            builder.append(" download_url = '" + vo.getDownloadUrl() + "',");
        }
        if (EmptyUtils.isNotEmpty(vo.getExpireTime())) {
            builder.append(" expire_time = '" + vo.getExpireTime() + "'");
        }
        if (builder.toString().endsWith(",")) {
            builder.deleteCharAt(builder.lastIndexOf(","));
        }
//        if (EmptyUtils.isNotEmpty(vo.getCreatorId())){
//            builder.append(" creator_id = '" + vo.getCreatorId() + "',");
//        }
        builder.append(" where user_uid = '" + vo.getUserUid() + "'");
        builder.append(" and user_type=0");
        sqlList.add(builder.toString());
        return sqlList;
    }

    private String queryUserList(String userUid, Integer pageSize, Integer pageNumber, String keyword) throws Exception {
        Integer accountType = getAccountType(userUid);
        String sql = "select u.nickname,u.register_time,u.latest_login_time,u.account_type,u.expire_time" +
                ",g.nickname creatorName,u.user_uid from g_users u " +
                " left join g_users g on g.user_uid = u.creator_id" +
                " where u.del_flag = 0 and u.user_type=0 and u.account_type!=2";
        if (accountType == 2) {

        } else if (accountType == 0) {
            sql += " and u.creator_id = '" + userUid + "'";
        } else {
            return gson.toJson(RetResult.failResult("无权限查看!"));
        }
        if (!CommonUtils.isStringEmpty(keyword)) {
            sql += " and (u.nickname like '%" + keyword + "%' or u.user_uid like '%" + keyword + "%')";
        }
        if (!Objects.isNull(pageNumber) && pageNumber > 0) {
            Integer pageNum = countPageNumber(pageNumber, pageSize);
            sql += " limit " + pageNum + "," + pageSize;
        }
        long total = 0L;
        StringBuilder builder = new StringBuilder();
        builder.append("select count(*) from g_users where del_flag = 0 and user_type=0");
        if (accountType == 0) {
            builder.append(" and creator_id = '" + userUid + "'");
        }
        if (!CommonUtils.isStringEmpty(keyword)) {
            builder.append(" and (nickname like '%" + keyword + "%' or user_uid like '%" + keyword + "%')");
        }
        Vector<Vector<?>> count = LogicProcessor2.db.queryData(builder.toString());
        if (!count.isEmpty()) {
            total = Long.parseLong((String) count.get(0).get(0));
        }

        Vector<Vector<?>> list = LogicProcessor2.db.queryData(sql);
        List<QueryUserResVO> vos = new ArrayList<>();
        for (Vector<?> v : list) {
            QueryUserResVO vo = new QueryUserResVO();
            int i = 0;
            String nickname = v.get(i).toString();
            String registerTime = v.get(++i).toString();
            String latestLoginTime = v.get(++i).toString();
            String type = v.get(++i).toString();
            String expireTime = v.get(++i).toString();
            String creatorName = v.get(++i).toString();
            String uid = v.get(++i).toString();
            vo.setUserUid(uid);
            vo.setNickname(nickname);
            vo.setRegisterTime(registerTime);
            vo.setAccountType(Integer.valueOf(type));
            vo.setLatestLoginTime(latestLoginTime);
            vo.setExpireTime(expireTime);
            vo.setCreatorName(creatorName);
            vos.add(vo);
        }
        PageData<QueryUserResVO> pageData = new PageData<>();
        pageData.setRecords(vos);
        pageData.setTotal(total);
        pageData.setPageNumber(pageNumber);
        pageData.setPageSize(list.size());
        return gson.toJson(RetResult.successResult("获取成功！", pageData));
    }

    private String getCreateId(String userUid) throws Exception {
        String s = "select creator_id from g_users where del_flag = 0 and user_uid = '" + userUid + "'";
        Vector<Vector<?>> vectors = LogicProcessor2.db.queryData(s);
        if (vectors.isEmpty()) {
            return null;
        }
        return (String) vectors.get(0).get(0);
    }

    private Integer getAccountType(String userUid) throws Exception {
        String s = "select account_type from g_users where del_flag = 0 and user_uid = '" + userUid + "'";
        Vector<Vector<?>> vectors = LogicProcessor2.db.queryData(s);
        if (vectors.isEmpty()) {
            return null;
        }
        return Integer.valueOf(vectors.get(0).get(0).toString());
    }

    private QueryUserResVO getUserByCreatorId(String userUid, String creatorId) throws Exception {
        String s = "select nickname,register_time,latest_login_time,account_type,expire_time," +
                "user_uid,user_type  from g_users where del_flag = 0 and creator_id = '" + creatorId + "' and user_uid = '" + userUid + "'";
        Vector<Vector<?>> vectors = LogicProcessor2.db.queryData(s);
        QueryUserResVO vo = new QueryUserResVO();
        if (vectors.isEmpty()) {
            vo.setUserUid("-1");
            return vo;
        }

        for (Vector<?> v : vectors) {
            int i = 0;
            String nickname = v.get(i).toString();
            String registerTime = v.get(++i).toString();
            String latestLoginTime = v.get(++i).toString();
            String type = v.get(++i).toString();
            String expireTime = v.get(++i).toString();
            String uid = v.get(++i).toString();
            String userType = v.get(++i).toString();
            vo.setUserUid(uid);
            vo.setNickname(nickname);
            vo.setRegisterTime(registerTime);
            vo.setAccountType(Integer.valueOf(type));
            vo.setLatestLoginTime(latestLoginTime);
            vo.setExpireTime(expireTime);
            vo.setUserType(Integer.valueOf(userType));
        }

        return vo;
    }

    private Integer countPageNumber(Integer pageNumber, Integer pagrSize) {
        return (pageNumber - 1) * pagrSize;
    }

    public void addUserInfo(List<String> sqls, List<Object[]> values, String userMail, String nickname,
                            String userPsw, String userSex, Date registerTime, Integer userStatus,
                            String userType, String accountType, String expireTime, String creatorId) {
        String sql = "insert into g_users (user_uid,user_mail,nickname,user_psw,user_sex,register_time,user_status," +
                "user_type,account_type,expire_time,creator_id) values (?,?,?,?,?,?,?,?,?,?,?)";
        sqls.add(sql);
        values.add(new Object[]{IdUtils.get8Uuid(), userMail, nickname, userPsw, userSex,
                registerTime, userStatus, userType, accountType, expireTime, creatorId});
    }

    /**
     * 判断添加账户是否存在
     */
    private boolean exitUser(String userMail) throws Exception {
        String sql = "select * from g_users where user_mail='" + userMail + "' and del_flag = 0";
        Vector<Vector<?>> vectors = LogicProcessor2.db.queryData(sql);
        return !vectors.isEmpty();
    }


}
